import time
from flask import  request,Response
from functools import wraps
import requests
# 自定义库
from utils.log import logger
from utils.message import send_json_msg
from utils.upload_about import set_files_msg
from utils.do_db import set_today_visit
# 获取ai信息接口参数
def get_ai_msg_parmams():
    p = None
    if request.is_json:
        if not 'msg' in request.json or request.json['msg'] == '':
            return  None
        p = request.json
        # p['files']=None
    else :
        p = request.form.to_dict()
        no_msg = not 'msg' in request.form or request.form['msg']==''
        no_files = len(request.files)==0
        if no_files==False:
            # 判断文件格式是否正确            
            p['files']=request.files
        if no_msg:
            if no_files:
                return None
            else:
                p['msg']="整理一下刚刚接收到的文件的内容"          
    return p

# 流式输出
def stream_output(chain,p,config,user_id):    

    try:         
        result = Response(generate_data(chain,p['msg'],p.get('type'),config,p['is_file_msg'],user_id), mimetype="text/event-stream")
        return  result,result.status_code
    except Exception as e:
        logger.error(f'返回出错{e}')
        return send_json_msg(203,f'返回出错{e}')


    
# 流式输出
def generate_data(chain,msg,_type,config,is_file_msg,user_id): 
        try:
            res = chain.stream({"input":msg}) if _type=='goods_info' else chain.stream({"input":msg},config)
            id=None
            for chunk in res: 
                id = id if id else chunk.id         
                yield chunk.content 
            id and set_files_msg(is_file_msg,id,user_id)
            name = _type if  _type=='goods_info' else 'ai_chat'
            set_today_visit(user_id,name)       
        except Exception as e :                        
            logger.error(f'stream_err:流式输出出错错误码：{e.response.status_code},错误信息：{e}')
            # code = e.response.status_code
            errMsg = f'error request:请求出错了,错误码：{e.response.status_code}'
            if e.response.status_code == 429 :
                errMsg = 'err 429,请求过于频繁，请1s后重试'  
            yield  errMsg 
# 非流式输出
def no_stream_output(chain,p,config,user_id):  
    _type = p.get('type')  
    try:
        ai_msg = chain.invoke({"input":p['msg']}) if _type=='goods_info' else chain.invoke({"input":p['msg']},config)
        set_files_msg(p['is_file_msg'],ai_msg.id,user_id)    
        name = _type if  _type=='goods_info' else 'ai_chat'
        is_success =  set_today_visit(user_id,name) 
        if is_success == False:
            return send_json_msg(202,'','访问权限更新失败')
        
        return send_json_msg(200,'',ai_msg.content)
    except Exception as e:
        logger.error(f'非流式输出发生错误{e}')
        return send_json_msg(203,f'非流式输出发生错误{e}') 
    
def timeout(seconds):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 记录请求开始时间
            start_time = time.time()
            # 执行请求处理函数
            result = func(*args, **kwargs)
            # 计算请求处理时间
            elapsed_time = time.time()- start_time
            # 如果请求处理时间超过设定的超时时间，则抛出异常
            if elapsed_time > seconds:
                raise Exception("Request timeout,请求超时")
            return result
        return wrapper
    return decorator

